import { Message } from '../models/Message.js';
import { Conversation } from '../models/Conversation.js';
import { AIService } from '../services/AIService.js';
import { StorageService } from '../services/StorageService.js';

export class ChatController {
    constructor(chatView, conversationListView) {
        this.chatView = chatView;
        this.conversationListView = conversationListView;
        this.aiService = new AIService();
        this.storageService = new StorageService();
        this.conversations = new Map();
        this.currentConversation = null;

        this.initialize();
    }

    async initialize() {
        await this.storageService.initialize();
        await this.loadConversations();
        this.setupEventListeners();

        // 如果没有会话，创建一个新的
        if (this.conversations.size === 0) {
            await this.createNewConversation();
        } else {
            // 选择最新的会话
            const lastConversation = Array.from(this.conversations.values())
                .sort((a, b) => b.createdAt - a.createdAt)[0];
            await this.switchConversation(lastConversation.id);
        }
    }

    async loadConversations() {
        this.conversations = await this.storageService.loadConversations();
        // 渲染所有会话
        this.conversations.forEach(conversation => {
            this.conversationListView.addConversation(conversation);
        });
    }

    setupEventListeners() {
        // 处理发送消息
        this.chatView.onSendMessage((content) => this.handleUserMessage(content));

        // 处理新建对话
        this.conversationListView.onNewChat(() => this.createNewConversation());

        // 处理选择对话
        this.conversationListView.onSelectConversation((id) => this.switchConversation(id));

        // 处理删除对话
        this.conversationListView.onDeleteConversation((id) => this.deleteConversation(id));
    }

    async createNewConversation() {
        const conversation = new Conversation();
        this.conversations.set(conversation.id, conversation);
        this.conversationListView.addConversation(conversation);
        await this.storageService.saveConversation(conversation);
        await this.switchConversation(conversation.id);
    }

    async switchConversation(conversationId) {
        this.currentConversation = this.conversations.get(conversationId);
        this.conversationListView.setActiveConversation(conversationId);

        // 清空并重新渲染消息
        this.chatView.messages.clear();
        this.currentConversation.getMessages().forEach(message => {
            this.chatView.renderMessage(message);
        });
    }

    async deleteConversation(conversationId) {
        const isCurrentConversation = this.currentConversation?.id === conversationId;
        this.conversations.delete(conversationId);
        await this.storageService.deleteConversation(conversationId);

        if (isCurrentConversation) {
            const nextConversation = this.conversations.values().next().value;
            if (nextConversation) {
                await this.switchConversation(nextConversation.id);
            } else {
                await this.createNewConversation();
            }
        }
    }

    async handleUserMessage(content) {
        // 禁用输入
        this.chatView.setLoading(true);

        // 添加用户消息
        const userMessage = new Message(content, 'user');
        this.currentConversation.addMessage(userMessage);
        this.chatView.renderMessage(userMessage);

        try {
            // 创建 AI 消息占位
            const aiMessage = new Message('', 'bot');
            this.currentConversation.addMessage(aiMessage);

            // 获取 AI 响应（流式）
            await this.aiService.generateResponse(content, (partialResponse) => {
                aiMessage.content = partialResponse;
                this.chatView.renderMessage(aiMessage, true);
            });

            // 完成后滚动到底部
            this.chatView.scrollToBottom();

            // 如果是新对话的第一条消息，生成标题
            if (this.currentConversation.messages.length === 2) {
                const title = await this.aiService.generateTitle(this.currentConversation.messages);
                this.currentConversation.title = title;
                const conversationElement = this.conversationListView.conversations.get(this.currentConversation.id);
                if (conversationElement) {
                    conversationElement.querySelector('.truncate').textContent = title;
                }
            }

            // 保存对话到本地存储
            await this.storageService.saveConversation(this.currentConversation);
        } catch (error) {
            console.error('Error getting AI response:', error);
            const errorMessage = new Message('抱歉，我遇到了一些问题。请稍后再试。', 'bot');
            this.currentConversation.addMessage(errorMessage);
            this.chatView.renderMessage(errorMessage);
        } finally {
            // 恢复输入
            this.chatView.setLoading(false);
        }
    }

    getCurrentConversation() {
        return this.currentConversation;
    }
}